/**
 * Copyright  (c) 2009-2010 Wilmar IT Service,  Inc.   
 * All  rights  reserved. 
 */
package com.wilmar.process.web.interceptors;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.wilmar.process.entity.User;
import com.wilmar.process.exception.NoUserSessionException;
import com.wilmar.process.web.spi.IUserSessionService;

/**
 * @author MaKuBEX Email:makubexnet@gmail.com
 * @version 1.0.0 Jun 21, 2010
 * @since 1.0.0
 * 
 */
public class SystemAuthorizationInterceptor extends AbstractProcessInterceptor {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = 3052202656090816128L;

	private static final Logger log = Logger
			.getLogger(SystemAuthorizationInterceptor.class);

	private IUserSessionService userSessionService;

	/**
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		log.debug("Getting current user!");
		try {
			this.getCurrentUser();
		} catch (NoUserSessionException e) {
			throw e;
		}
		return invocation.invoke();
	}

	/**
	 * 获取当前用户
	 * 
	 * @return 当前用户
	 * @throws NoUserSessionException
	 *             如果无法获取用户相关信息
	 */
	protected User getCurrentUser() throws NoUserSessionException {
		User currentUser = null;
		try {
			currentUser = this.userSessionService.getCurrentUserObject();
			if (currentUser == null) {
				ActionContext actionContext = ActionContext.getContext();
				currentUser = this.userSessionService
						.getCurrentUserObject(actionContext.getSession());
			}
			if (currentUser == null) {
				currentUser = this.userSessionService
						.getCurrentUserObject(ServletActionContext.getRequest()
								.getSession());
			}
		} catch (NoUserSessionException e) {
			try {
				ActionContext actionContext = ActionContext.getContext();
				currentUser = this.userSessionService
						.getCurrentUserObject(actionContext.getSession());
			} catch (NoUserSessionException e2) {
				currentUser = this.userSessionService
						.getCurrentUserObject(ServletActionContext.getRequest()
								.getSession());
			}
		}
		return currentUser;
	}

	/**
	 * @return the userSessionService
	 */
	public IUserSessionService getUserSessionService() {
		return userSessionService;
	}

	/**
	 * @param userSessionService
	 *            the userSessionService to set
	 */
	public void setUserSessionService(IUserSessionService userSessionService) {
		this.userSessionService = userSessionService;
	}

}
